/**
 * radio表单快速请求
 * radio
 */
import React, { useEffect, useState } from 'react';
import PropTypes from 'prop-types';
import { Radio, Spin, Input, Select, InputNumber } from 'antd';
import { getEffectSource, everyRequire } from './utils';

const { Option } = Select;

// const { Option } = Select;
const RadioForm = React.forwardRef(
    (
        {
            form = {},
            onChange,
            value,
            getData,
            params,
            filterItem = null, // 设置过滤指定项
            radioOther = null, // 设置radio需要绑定显示其他输入框
            inputProps = {}, // 设置其他需要显示输入框的样式和初始值
            ...rest
        },
        ref
    ) => {
        const { getFieldDecorator } = form;

        // const { getFieldDecorator = '' } = form;
        const { radioProps, fieldsName, requireParam } = rest;
        const { disabled = false } = radioProps;
        const { radioValue, radioTitle } = fieldsName;
        const {
            initial = '',
            inputStyle = {},
            leaveNewEmployeeLimit = 1,
            leaveNewEmployeeLimitUnit = 'day',
            disalbedVallue = false
        } = inputProps;
        const [radioList, setRadioList] = useState([]);
        const [loading, setLoading] = useState(false);
        const [entryLimitUnit, setEntryLimitUnit] = useState([]);
        const fetchList = async () => {
            if (!everyRequire(params, requireParam)) return;
            setLoading(true);
            const result = await getData(params);
            const result2 = await getData({ dictCode: 'afterEntryLimitUnit' });
            setLoading(false);
            setRadioList(result || []);
            setEntryLimitUnit(result2 || []);
        };
        const handleChange = (e = '') => {
            onChange(e);
        };
        const limitDecimals = (values = 1) => {
            if (values) {
                return parseInt(values, 10);
            }
            return '';
        };
        const changeValue = () => {
            setTimeout(() => {
                if (form.getFieldValue('leaveNewEmployee') === 'after_entry_limit') {
                    if (
                        form.getFieldValue('leaveNewEmployeeLimit') === null ||
                        form.getFieldValue('leaveNewEmployeeLimit') === undefined
                    ) {
                        form.setFields({
                            leaveNewEmployee: {
                                value: 'after_entry_limit',
                                errors: [new Error('仅支持输入1-999的整数！')]
                            }
                        });
                    } else if (
                        form.getFieldValue('leaveNewEmployeeLimitUnit') === null ||
                        form.getFieldValue('leaveNewEmployeeLimitUnit') === undefined
                    ) {
                        form.setFields({
                            leaveNewEmployee: {
                                value: 'after_entry_limit',
                                errors: [new Error('请选择单位！')]
                            }
                        });
                    } else {
                        form.setFields({
                            leaveNewEmployee: {
                                value: 'after_entry_limit',
                                errors: null
                            }
                        });
                    }
                }
            })
        };
        useEffect(() => {
            fetchList();
        }, getEffectSource(params));

        const gapStyle = { marginTop: 8 };
        return (
            <Spin spinning={loading}>
                <Radio.Group
                    ref={ref}
                    // see: https://github.com/ant-design/ant-design/issues/6543
                    value={value}
                    onChange={handleChange}
                    {...radioProps}
                >
                    {radioList.map(item => {
                        if (item[radioTitle] === filterItem) {
                            return null;
                        }
                        // 这里用于假期设置的时候，新员工请假字段
                        if (item[radioValue] === 'after_entry_limit') {
                            return (
                                <div style={gapStyle}>
                                    <Radio value={item[radioValue]} key={item.id}>
                                        入职
                                        {getFieldDecorator &&
                                            getFieldDecorator('leaveNewEmployeeLimit', {
                                                initialValue: leaveNewEmployeeLimit
                                            })(
                                                <InputNumber
                                                    min={1}
                                                    max={999}
                                                    style={{ width: '70px', margin: '0 8px' }}
                                                    disabled={disalbedVallue}
                                                    formatter={limitDecimals}
                                                    parser={limitDecimals}
                                                    onChange={() => {
                                                        changeValue();
                                                    }}
                                                />
                                            )}
                                        {getFieldDecorator &&
                                            getFieldDecorator('leaveNewEmployeeLimitUnit', {
                                                initialValue:
                                                    leaveNewEmployeeLimitUnit === '' ? null : leaveNewEmployeeLimitUnit
                                            })(
                                                <Select
                                                    disabled={disalbedVallue}
                                                    onChange={() => {
                                                        changeValue();
                                                    }}
                                                    style={{ width: '60px', marginRight: '8px' }}
                                                >
                                                    {entryLimitUnit &&
                                                        entryLimitUnit.map(list => (
                                                            <Option value={list.dictValue}>{list.dictName}</Option>
                                                        ))}
                                                </Select>
                                            )}
                                        后可请假
                                    </Radio>
                                </div>
                            );
                        }
                        if (item[radioValue] === radioOther) {
                            return (
                                <span>
                                    <Radio value={item[radioValue]} key={item.id}>
                                        {item[radioTitle]}
                                    </Radio>
                                    <Input style={inputStyle} value={initial} disabled={disabled} />
                                </span>
                            );
                        }
                        return (
                            <span>
                                <Radio value={item[radioValue]} key={item.id}>
                                    {item[radioTitle]}
                                </Radio>
                            </span>
                        );
                    })}
                </Radio.Group>
            </Spin>
        );
    }
);

RadioForm.propTypes = {
    onChange: PropTypes.func,
    /**
     * request 请求参数
     */
    params: PropTypes.object,
    /**
     * 获取数据
     */
    getData: PropTypes.func,
    /**
     * 自定义字段
     */
    fieldsName: PropTypes.object,
    // radio 属性
    radioProps: PropTypes.object
};

RadioForm.defaultProps = {
    onChange: () => {},
    radioProps: {},
    params: {},
    getData: () => {},
    fieldsName: {}
};

export default RadioForm;
